import http.client, random, json


class WoniuSalesTest:
    def __init__(self):
        self.host = 'localhost'
        self.port = 8081
        self.cookie = ''

    def login(self):
        conn = http.client.HTTPConnection(self.host, self.port)
        data = 'username=admin&password=admin123&verifycode=0000'
        headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        conn.request('POST', '/WoniuSales1.4/user/login', body=data, headers=headers)
        response = conn.getresponse()
        content = response.read().decode()
        print(content)

        for header in response.getheaders():
            # print(header[0])
            # print(header[a.txt].split(';')[0] + ';')
            if header[0] == 'Set-Cookie':
                self.cookie += header[1].split(';')[0] + ';'
        # print(self.cookie)

    def add_customer(self):
        self.sequence = random.randint(10000, 99999)
        conn = http.client.HTTPConnection(self.host, self.port)
        headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie': self.cookie}
        data = 'customername=用户_%d&customerphone=138000%d&childsex=男&childdate=2018-10-09&creditkids=11&creditcloth=22' % (
        self.sequence, self.sequence)
        body = data.encode()
        conn.request('POST', '/WoniuSales1.4/customer/add', body=body, headers=headers)
        response = conn.getresponse()
        content = response.read().decode()
        return content

    def query_customer(self):
        conn = http.client.HTTPConnection(self.host, self.port)
        headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie': self.cookie}
        body = 'customerphone=138000%d&page=a.txt' % self.sequence
        conn.request('POST', '/WoniuSales1.4/customer/search', body=body, headers=headers)
        response = conn.getresponse()
        content = response.read().decode()
        return content
        # print(type(content))
        # print(json.loads(content)[0]['customerphone'])

    def test_add_member(self):
        content = self.add_customer()
        if content == 'add-successful':
            print('会员添加成功!')
        else:
            print('会员添加失败!')

    def test_customer_query(self):
        content = self.query_customer()
        newcontent = json.loads(content)  # json格式转为Python对象
        phone = newcontent[0]['customerphone']
        if str(self.sequence) in phone:
            print('查询成功!')
        else:
            print('查询失败!')


if __name__ == '__main__':
    wt = WoniuSalesTest()
    wt.login()
    wt.test_add_member()
    wt.test_customer_query()
